package cn.aitstone.pet.service.impl;

import cn.aitstone.basic.service.impl.BaseServiceImpl;
import cn.aitstone.pet.domain.PetType;
import cn.aitstone.pet.mapper.PetTypeMapper;
import cn.aitstone.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sheldon
 * @since 2022-07-16
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;
    
    @Override
    public List<PetType> tree() {
        List<PetType> petTypeAll = petTypeMapper.loadAll();
        ArrayList<PetType> petTypeTree = new ArrayList<>();
        HashMap<Long, PetType> petTypeMap = new HashMap<>();
        for (PetType petType : petTypeAll) {
            petTypeMap.put(petType.getId(), petType);

        }
        for (PetType petTypeTemp : petTypeAll){
            if(petTypeTemp.getPid() == null){
                petTypeTree.add(petTypeTemp);
            } else {
                // 从map集合中获取到父对象，将自己添加到父对象的children集合中
                PetType petType = petTypeMap.get(petTypeTemp.getPid());
                if (petType != null){
                    petType.getChildren().add(petTypeTemp);
                }
            }

        }
        return petTypeTree;
    }


    @Override
    public void save(PetType petType) {
        petTypeMapper.save(petType);
        System.out.println("验证"+petType);
        // 给dirPath拼接值
        String dirPath = "";
        if (petType.getParent().getId() == null){
            // 如果parent对象为Null,说明他是顶级对象，那么dirPath就是他自己的主键id
            dirPath = "/" + petType.getId();
        }else {
            // 否则他就有上级部门，那么我们需要查询到上级部门的对象，获取到上级部门的dirpath，拼接我自己的id，就是我的dirpath
            PetType parentPetType = petTypeMapper.loadById(petType.getParent().getId());
            if(parentPetType != null){
                dirPath = parentPetType.getDirPath() + "/" + petType.getId();
            }
        }
        petType.setDirPath(dirPath);
        System.out.println("验证后" + petType);
        petTypeMapper.update(petType);
    }

    @Override
    public void update(PetType petType) {
        // 给dirPath拼接值
        String dirPath = "";
        if (petType.getParent().getId() == null){
            // 如果parent对象为Null,说明他是顶级对象，那么dirPath就是他自己的主键id
            dirPath = "/" + petType.getId();
        }else {
            // 否则他就有上级部门，那么我们需要查询到上级部门的对象，获取到上级部门的dirpath，拼接我自己的id，就是我的dirpath
            PetType parentPetType = petTypeMapper.loadById(petType.getParent().getId());
            if(parentPetType != null){
                dirPath = parentPetType.getDirPath() + "/" + petType.getId();
            }
        }
        petType.setDirPath(dirPath);
        petTypeMapper.update(petType);
    }
}
